# -*- coding: utf-8 -*-
from datetime import timedelta
from time import time
from utils.operators.volume_rick_sql_operator import VolumeRichSqlSensor
from spmi_volume.dm.dm_5_volume import dm_5_volume


label = f"doris_spmi_dws__dws_volume_cost_kilogram_sum_m{int(time())}"
timeout = timedelta(minutes=30).seconds
doris_spmi_dws__dws_volume_cost_kilogram_sum_m = VolumeRichSqlSensor(
    task_id='doris_spmi_dws__dws_volume_cost_kilogram_sum_m',
    pool='broker_load_pool',
    email=['yushuo@jtexpress.com','yl_bigdata@yl-scm.com'],
    conn_id='doris',
    pre_sql=f"""
    TRUNCATE TABLE spmi_dws.dws_volume_cost_kilogram_sum_m PARTITION (p{{{{ execution_date | add_month(-1) | cst_month_nodash }}}},p{{{{ execution_date | cst_month_nodash }}}});
    LOAD LABEL spmi_dws.{label} (
        DATA INFILE(
                    "hdfs://{{{{ var.value.hadoop_namespace }}}}/dw/hive/spmi_dm.db/external/dm_volume_cost_kilogram_sum_m/mt={{{{ execution_date | add_month(-1) | cst_month_dash }}}}/*",
                    "hdfs://{{{{ var.value.hadoop_namespace }}}}/dw/hive/spmi_dm.db/external/dm_volume_cost_kilogram_sum_m/mt={{{{ execution_date | cst_month_dash }}}}/*"
                    )
        INTO TABLE dws_volume_cost_kilogram_sum_m  
    FORMAT AS 'PARQUET'
    )
    WITH BROKER '{{{{ var.json.doris_brokers | random_choice }}}}'
    PROPERTIES ('timeout'='{timeout}', 'max_filter_ratio'='0.0')""",
    poke_sql=f"SHOW LOAD FROM spmi_dws WHERE label = '{label}' ORDER BY CreateTime DESC LIMIT 1",
    sql_on_kill=f"CANCEL LOAD FROM spmi_dws WHERE LABEL = '{label}'",
    success=lambda r: r[2] == 'FINISHED',
    failure=lambda r: (r[2] is not None and r[2] == 'CANCELLED', str(r[7])),
    poke_interval=60,
    execution_timeout=timedelta(seconds=timeout + 120), )
doris_spmi_dws__dws_volume_cost_kilogram_sum_m << dm_5_volume